package cn.hct.springboot_pro.controller;

import cn.hct.springboot_pro.entity.Orders;
import cn.hct.springboot_pro.service.ItemService;
import cn.hct.springboot_pro.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/Order")
public class OrderController {

    @Autowired
    OrderService orderService;
    @Autowired
    ItemService itemService;

    @RequestMapping("/addOrder")
    public String addOrder(Model model, int item_id, Orders order, HttpSession session){
        /*下单id*/
        int user_id= (int) session.getAttribute("user_id");
        //当前获取时间
        Date d = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String creat_time = df.format(d);

        int i = orderService.addOrder(item_id,user_id,order.getItem_name(),order.getOrder_price(),order.getConsignee(),order.getAddr(),order.getContact_way(),creat_time);

        int j = itemService.updateIStateByid(item_id,0);

        if (i!=0 && j!=0){
            Orders orderNew = orderService.getOrderByTimeAndItem(item_id,creat_time);
            int order_id=orderNew.getOrder_id();
            return "redirect:/Order/orderCommit?order_id="+order_id;
        }
        else{
            model.addAttribute("message","对不起,你的订单未提交成功，具体原因不清楚，可以联系客服小黄了解一下：2359220243@qq.com");
            return "public/message";
        }

    }
    @RequestMapping("/orderCommit")
    public String orederCommit(Model model,int order_id){
      // int order_id=(int) model.getAttribute("order_id");
       Orders orderNew = orderService.getOrderById(order_id);
       model.addAttribute("orderNew",orderNew);
       return "user/orderCommit";
    }

    @RequestMapping("/userDeleteOrder")
    public String userDeleteOrder(int order_id,Model model){

        Orders orders = orderService.getOrderById(order_id);
        int j = itemService.updateIStateByid(orders.getItem_id(),1);
        int i = orderService.deleteOrderById(order_id);
        if (i!=0 && j!=0){
            return "/user/user-news";
        }
        else {
            model.addAttribute("删除失败，请联系客服中心");
            return "";
        }


    }
}
